﻿using AutoMapper;
using CK.Sprite.Cache;
using CK.Sprite.Framework;
using JetBrains.Annotations;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CK.Sprite.Form.Core
{
    public class ObjectMethodLocalCache : LocalCache<ObjectMethodDto>
    {
        public override string CacheKey => CommonConsts.ObjectMethodCacheKey;

        public override List<ObjectMethodDto> GetAll(string applicationCode)
        {
            if (!LocalCacheContainer.IsEnabledLocalCache)
            {
                return _serviceProvider.DoDapperService(DefaultDbConfig, (unitOfWork) =>
                {
                    return GetObjectMethodDtos(applicationCode, unitOfWork);
                });
            }
            else
            {
                return (List<ObjectMethodDto>)LocalCacheContainer.Get($"{CommonConsts.SpriteFormCachePreKey}-{applicationCode}_{CacheKey}", key =>
                {
                    return _serviceProvider.DoDapperService(DefaultDbConfig, (unitOfWork) =>
                    {
                        return GetObjectMethodDtos(applicationCode, unitOfWork);
                    });
                });
            }
        }

        private List<ObjectMethodDto> GetObjectMethodDtos(string applicationCode, IUnitOfWork unitOfWork)
        {
            var objectMethodRepository = ConnectionFactory.GetConnectionProvider(DefaultDbConfig.ConnectionType).GetRepository<IObjectMethodRepository>(unitOfWork);
            var objectMethods = objectMethodRepository.GetAllObjectMethodByApplicationCode(applicationCode);
            List<ObjectMethodDto> objectMethodDtos = Mapper.Map<List<ObjectMethodDto>>(objectMethods);

            objectMethodDtos.ForEach(r =>
            {
                var objectMethod = objectMethods.First(t => t.Id == r.Id);
                r.CommonParamDtos = string.IsNullOrEmpty(objectMethod.ParamJsons) ? null : SerializeService.DeserializeObject<List<CommonParamDto>>(objectMethod.ParamJsons);
            });

            return objectMethodDtos;
        }
    }
}
